package com.hp.it.server.listener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.hp.it.server.configuration.GobalConstant;
import com.hp.it.server.configuration.ReportConstant;
import com.hp.it.server.context.ProjectContext;

public class ContextInitializerListener implements ServletContextListener
{
	public void contextInitialized(ServletContextEvent sce)
	{
		/* workspace directory */
		File workspace = new File(System.getProperty("user.home") + File.separator + GobalConstant.HOME_DIR
				+ File.separator + GobalConstant.WORKSPACE);
		if (!workspace.exists())
		{
			workspace.mkdirs();
		}

		if (workspace.isDirectory())
		{
			for (File projectDir : workspace.listFiles())
			{
				if (!projectDir.isDirectory())
				{
					continue;
				}

				for (File file : projectDir.listFiles())
				{
					if (file.isFile() && file.getName().equalsIgnoreCase(GobalConstant.CONFIG_PROPERTIES))
					{
						// String extension =
						// fileName.substring(fileName.lastIndexOf(".") + 1);
						try
						{
							Properties properties = new Properties();
							FileInputStream fis=new FileInputStream(file);
							properties.load(fis);
							ProjectContext.setProperties((properties.getProperty(ReportConstant.KEE)),
									properties);
							fis.close();
						} catch (FileNotFoundException e)
						{
							e.printStackTrace();
						} catch (IOException e)
						{
							e.printStackTrace();
						}
					}
				}
			}
		}

		/* template directory */
		File templateDir = new File(System.getProperty("user.home") + File.separator + GobalConstant.HOME_DIR
				+ File.separator + GobalConstant.TEMPLATE_DIR);
		if (!templateDir.exists())
		{
			templateDir.mkdir();
		}
	}

	public void contextDestroyed(ServletContextEvent sce)
	{

	}
	
}
